angular.module('activities.controllers')

.controller 'AccumulatePointsCtrl', ($scope, $rootScope, RemoteSrv, SendMessage, Toast, Config, AccumulatePoints)->
  SendMessage.send_to_app('get_account')

  Zepto.initPullToRefresh('#activity-unlock-page')

  $scope.presents = AccumulatePoints.all

  $scope.changeType = (type)->
    $scope.type = type
      
  Zepto("#city-picker").cityPicker({
    toolbarTemplate: '<header class="bar bar-nav">\
    <button class="button button-link pull-right close-picker">确定</button>\
    <h1 class="title">选择收货地址</h1>\
    </header>'
  })
  $scope.hideKeyboard = ()->
    $('input').focusout()
    $('#city-picker').focus()
    return

  $('.input-code').focus ()->
    Zepto.closeModal(".picker-modal.modal-in")
    return

  $scope.getAccount = ()->
    activity_sidao.storage.account()

  $scope.info = {}
  $scope.info.times = 0
  $scope.width = 0
  $scope.progress = 0
  $scope.star_num = 0
  $scope.imgs = []
  $scope.imgs2 = []
  $scope.text1 = '领取'
  $scope.text2 = '领取'
  $scope.text3 = '领取'
  $scope.spreadNum = 0

  $scope.share = ()->
    wechat_share_data = {
      title: "全民参与 狂欢双十二",
      desc: "诱人收益与惊喜大礼共享，Iphone7/苹果ipod/暴风VR眼镜/大额加息券等免费拿，100%中奖率！",
      img_url: "https://www.sidaojinfu.com/mobile/img/icon.jpg",
      id: "001",
      messageExt: "君财金服邀请",
      messageAction: "<action>dotalist</action>"
      link: "#{Config.longly_page_url}activityUnlock?promotion_code=#{$scope.getAccount().promotion_code}"
      media: {
        #  type: Wechat.Type.LINK,
        link: "#{Config.longly_page_url}activityUnlock?promotion_code=#{$scope.getAccount().promotion_code}"
      }
    }
    window.furionPostMessage.share_wechat(wechat_share_data)

  getSessionString = ()->
    return getQueryString('session_id')

  getQueryString = (name)->
    r = window.location.hash
    reg = new RegExp("\\?#{name}\=\\S+")
    r = r.match(reg)
    return null if !r
    r = r[0].split("=")
    r = r[1] if r
    r

  if !$scope.getAccount().session_id
    Zepto.destroyPullToRefresh('#activity-unlock-page')
    
  $(document).on 'refresh', '#activity-unlock-page', (e)->
    initPage()

  $scope.$on '$viewContentLoaded', ()->
    # getRecord()
    $scope.type ||= 'contactus'
    $scope.changeType($scope.type)

    is_init = false
    session_id = getSessionString()
    if session_id
      window.localStorage["rt_session_id"] = session_id
      RemoteSrv.getAccountInfo().done (resp)->
        resp.data.account.session_id = session_id
        window.localStorage['rt-account-activity'] = JSON.stringify(resp.data.account)
        initPage()

  is_init = false
  initPage = ()->
    $scope.info = {}
    $scope.info.times = 0
    $scope.width = 0
    $scope.progress = 0
    $scope.star_num = 0
    $scope.imgs = []
    $scope.imgs2 = []
    session_id = $scope.getAccount().session_id
    return unless session_id?
    console.log "initPage"
    #return if is_init
    console.log '1111'
    is_init = true
    if !$scope.getAccount().session_id
      Toast.show "您尚未登录，分享不增加抽奖次数"
      $rootScope.loading = false
    else
      getActivityInfo()
      # getActivityRecords()
      # $scope.share()
      # $scope.checkPresent()
    Zepto.pullToRefreshDone('#activity-unlock-page')

  getRecord = ()->
    code = getQueryString("promotion_code")
    if code
      RemoteSrv.shareSuccess(code, wuyi_activity_cname).done (resp)->
        if resp.status.success
          console.debug "ok"
      .always ()->
        Zepto.pullToRefreshDone('#activity-unlock-page')

  getActivityInfo = ()->
    if !$scope.getAccount().session_id
      Toast.show '您尚未登录'
      return
    RemoteSrv.getActivityInfo(wuyi_activity_cname).done (resp)->
      if resp.status.success
        $scope.info = resp.data
        $scope.info.times = $scope.info.times

        for key, value of $scope.info.conditions
          continue if key == 'amount'
          if key && value >= 5000
            $scope.spreadNum += 1
        
    .always ()->
      Zepto.pullToRefreshDone('#activity-unlock-page')

    RemoteSrv.getPresentRecords(wuyi_activity_cname).done (resp)->
      if resp.status.success
        $scope.records = resp.data.present_records
        for p in resp.data.present_records
          if p.present.cname == "wuyi_of_2017_present_1"
            $scope.text1 = '已领取'
          else if p.present.cname == "wuyi_of_2017_present_2"
            $scope.text2 = '已领取'
          else if p.present.cname == "wuyi_of_2017_present_3"
            $scope.text3 = '已领取'
      else
        Toast.show resp
    .fail( (err) ->
      console.log err
      msg = JSON.parse(err.responseText)
      Toast.show msg.status.msg
    )

  $scope.getPresent = (present_cname) ->
    if !$scope.getAccount().session_id
      Toast.show '您尚未登录'
      return
    return if ($scope.text1 == '已领取') && (present_cname == 'wuyi_of_2017_present_1')
    return if ($scope.text2 == '已领取') && (present_cname == 'wuyi_of_2017_present_2') 
    return if ($scope.text3 == '已领取') && (present_cname == 'wuyi_of_2017_present_3')
    RemoteSrv.givePresent('wuyi_of_2017', 'wuyi_of_2017', present_cname).done (resp)->
      if resp.status.success
        Toast.show '您已成功领取'
        getActivityInfo()
  return


